package com.example.netcapture.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.netcapture.dto.PacketInfoDto;
import com.example.netcapture.entity.PacketInfo;
import com.example.netcapture.service.PacketQueryService;
import com.example.netcapture.utils.ContentAnalyzer;
import com.example.netcapture.utils.TcpSessionManager;
import com.example.netcapture.utils.TcpStreamReassembler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/session")
@RequiredArgsConstructor
public class SessionController {
    
    private final PacketQueryService packetQueryService;

    @GetMapping("/reassemble/{sessionId}")
    public ResponseEntity<Map<String, Object>> reassemble(@PathVariable String sessionId) {
        try {
            TcpSessionManager.TcpSession session = TcpSessionManager.getOrCreateSession(sessionId);
            String streamData = session.getReassembledStream();

            if (streamData == null || streamData.isEmpty()) {
                return ResponseEntity.noContent().build();
            }

            // 分析内容类型和可能的文件名
            ContentAnalyzer.FileInfo fileInfo = ContentAnalyzer.analyzeContent(streamData);

            Map<String, Object> result = Map.of(
                    "streamData", streamData,
                    "contentType", fileInfo.getContentType(),
                    "fileName", fileInfo.getFileName(),
                    "fileSize", fileInfo.getFileSize()
            );

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    @GetMapping("/export/{sessionId}")
    public ResponseEntity<byte[]> exportFile(@PathVariable String sessionId) {
        try {
            // 优先从文件数据块获取二进制文件
            byte[] fileData = TcpSessionManager.getFileDataBySession(sessionId);

            if (fileData != null && fileData.length > 0) {
                // 二进制文件导出
                TcpSessionManager.TcpSession session = TcpSessionManager.getOrCreateSession(sessionId);
                TcpSessionManager.FileSessionInfo fileInfo = session.getFileSessionInfo();

                String fileName = "exported_file." + getFileExtension(fileInfo.fileType);

                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                headers.setContentDispositionFormData("attachment", fileName);
                headers.setContentLength(fileData.length);

                return ResponseEntity.ok()
                        .headers(headers)
                        .body(fileData);
            } else {
                // 文本内容导出
                TcpSessionManager.TcpSession session = TcpSessionManager.getOrCreateSession(sessionId);
                String streamData = session.getReassembledStream();

                if (streamData == null || streamData.isEmpty()) {
                    return ResponseEntity.notFound().build();
                }

                // 分析内容类型
                ContentAnalyzer.FileInfo fileInfo = ContentAnalyzer.analyzeContent(streamData);

                // 提取纯文件内容
                String fileContent = ContentAnalyzer.extractFileContent(streamData, fileInfo.getContentType());
                byte[] fileBytes;

                if (fileInfo.getContentType().equals("binary") ||
                        fileInfo.getContentType().equals("base64")) {
                    // 对于二进制或base64内容，直接使用原始字节
                    fileBytes = fileContent.getBytes(StandardCharsets.ISO_8859_1);
                } else {
                    // 文本内容使用UTF-8编码
                    fileBytes = fileContent.getBytes(StandardCharsets.UTF_8);
                }

                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                headers.setContentDispositionFormData("attachment", fileInfo.getFileName());
                headers.setContentLength(fileBytes.length);

                return ResponseEntity.ok()
                        .headers(headers)
                        .body(fileBytes);
            }

        } catch (Exception e) {
            log.error("导出文件失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    // 根据文件类型获取扩展名
    private String getFileExtension(String fileType) {
        if (fileType == null) return "bin";

        switch (fileType.toUpperCase()) {
            case "JPEG": case "JPG": return "jpg";
            case "PNG": return "png";
            case "GIF": return "gif";
            case "PDF": return "pdf";
            case "ZIP": return "zip";
            case "RAR": return "rar";
            case "GZIP": return "gz";
            case "BMP": return "bmp";
            case "TIFF": return "tiff";
            default: return "bin";
        }
    }

    // 添加HTTP body提取方法
    private String extractHttpBody(String content) {
        int headerEnd = content.indexOf("\r\n\r\n");
        if (headerEnd == -1) {
            headerEnd = content.indexOf("\n\n");
        }

        if (headerEnd != -1) {
            return content.substring(headerEnd + 4).trim();
        }

        return content;
    }
}